import {createSlice} from "@reduxjs/toolkit"
import {getList} from "../../api/bill"

let userInfo
if(localStorage.getItem("userToken")){
    userInfo = JSON.parse(localStorage.getItem("userToken"))
}
const billStore = createSlice({
    name: "billStore",
    initialState:{
        billList:[],
        userInfo
    },
    reducers:{
        setBillList(state,action){
            console.log("保存用户账单信息到redux~",action);
            state.billList = action.payload
        },
        setUserInfo(state,action){
            console.log("保存用户信息到redux~",action);
            state.userInfo = action.payload
        }
    }
})


const {setBillList,setUserInfo} = billStore.actions

function getBillListSync(){
    return async (dispatch,getState)=>{
        const state = getState()
        console.log("获取最新的账单数据",state);
        if(state.billStore.userInfo){
            const {id} = state.billStore.userInfo
            const result = await getList({id})  // 获取账单数据
            dispatch(setBillList(result))
        }
    }
}
const billReducer = billStore.reducer
export {setBillList,setUserInfo,billReducer,getBillListSync}